package com.shj.web.config;

import com.shj.web.security.JwtAuthenticationTokenFilter;
import com.shj.web.security.MyAccessDecisionManager;
import com.shj.web.security.MyFilterInvocationSecurityMetadataSource;
import com.shj.web.security.UserAuthenticationProvider;
import com.shj.web.security.handler.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

/**
 * @Description TODO spring security核心配置
 * @Author songhuajian
 * @Date 2020/3/13 15:17
 **/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 自定义登录成功处理器
     */
    @Autowired
    private UserLoginSuccessHandler userLoginSuccessHandler;
    /**
     * 自定义登录失败处理器
     */
    @Autowired
    private UserLoginFailureHandler userLoginFailureHandler;
    /**
     * 自定义注销成功处理器
     */
    @Autowired
    private UserLogoutSuccessHandler userLogoutSuccessHandler;
    /**
     * 自定义暂无权限处理器处理器
     */
    @Autowired
    private UserAuthAccessDeniedHandler userAuthAccessDeniedHandler;
    /**
     * 自定义未登录处理器
     */
    @Autowired
    private UserAuthenticationEntryPointHandler userAuthenticationEntryPointHandler;
    /**
     * 自定义登录逻辑验证器
     */
    @Autowired
    private UserAuthenticationProvider userAuthenticationProvider;
    /**
     * 自定义权限决策管理器
     */
    @Autowired
    private MyAccessDecisionManager myAccessDecisionManager;
    /**
     * 自定义权限资源过滤器
     */
    @Autowired
    private MyFilterInvocationSecurityMetadataSource myFilterInvocationSecurityMetadataSource;

    @Autowired
    private UserLogoutHandler userLogoutHandler;

    /**
     * @description 加密方式
     * @author songhuajian
     * @date 2020/3/13 15:23
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){ return new BCryptPasswordEncoder();}


    /**
     * @description 设置自定义验证登录
     * @author songhuajian
     * @date 2020/3/13 15:26
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(userAuthenticationProvider);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 不需要矩形权限认证的请求或资源（从配置文件中读取）
            .authorizeRequests()
                .antMatchers(JwtConfig.antMatchers.split(",")).permitAll()
                //权限决策管理配置
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setAccessDecisionManager(myAccessDecisionManager);
                        o.setSecurityMetadataSource(myFilterInvocationSecurityMetadataSource);
                        return o;
                    }
                })
            .and()
            // 登录处理
            .formLogin()
                .loginProcessingUrl("/login")
                // 登录失败处理器
                .failureHandler(userLoginFailureHandler)
                // 登录成功处理器
                .successHandler(userLoginSuccessHandler)
            .and()
            .httpBasic()
                // 未登录处理器
                .authenticationEntryPoint(userAuthenticationEntryPointHandler)
            .and()
            // 注销处理
            .logout()
                .logoutUrl("/logout")
                .addLogoutHandler(userLogoutHandler)
                .logoutSuccessHandler(userLogoutSuccessHandler)
            .and()
            // 没有权限处理器
            .exceptionHandling()
                .accessDeniedHandler(userAuthAccessDeniedHandler)
            .and()
            // 开启跨域
            .cors()
            .and()
            // 取消跨站请求伪造防护
            .csrf().disable();

        // 基于token不需要session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 禁用缓存
        http.headers().cacheControl();
        // 添加JWT过滤器
        http.addFilter(new JwtAuthenticationTokenFilter(authenticationManager()));
    }

    /**
     * @description 设置资源不拦截
     * @author songhuajian
     * @date 2020/1/11 19:59
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/swagger-ui.html")
                .antMatchers( "/swagger-resources/**")
                .antMatchers("/v2/api-docs")
                .antMatchers("/configuration/ui")
                .antMatchers("/configuration/security")
                .antMatchers("/webjars/**");
    }
}
